package com.ys.http.network;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;
import java.util.Set;

public class JsonBuilder {

    private final JSONObject obj;

    private JsonBuilder() {
        obj = new JSONObject();
    }

    public static JsonBuilder newBuilder() {
        return new JsonBuilder();
    }

    public JsonBuilder add(String key, Number value) {
        if (isValidate(key, value)) {
            obj.put(key, value);
        }
        return this;
    }

    public JsonBuilder add(String key, boolean value) {
        if (isValidate(key, value)) {
            obj.put(key, value);
        }
        return this;
    }

    public JsonBuilder add(String key, String value) {
        if (isValidate(key, value)) {
            obj.put(key, value);
        }
        return this;
    }

    public JsonBuilder add(String key, Object value) {
        if (isValidate(key, value)) {
            obj.put(key, value);
        }
        return this;
    }

    public JsonBuilder add(Object value) {
        if (value != null) {
            JSONObject object = JSON.parseObject(JSON.toJSONString(value));
            Set<Map.Entry<String, Object>> entrySet = object.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                obj.put(entry.getKey(), entry.getValue());
            }
        }
        return this;
    }

    private boolean isValidate(String name, Object value) {
        return name != null && value != null;
    }

    public JSONObject get() {
        return obj;
    }

    @Override
    public String toString() {
        return obj.toJSONString();
    }

    public Object build() {
        return obj;
    }
}
